package org.runecore.rs2.net.sql;

import java.io.FileInputStream;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.runecore.Launch;

/**
 * RuneCore
 * Oct 16, 2011
 * @author Harry Andreas<Harry@RuneCore.org>
 */

public class SQLConnection {
	
	/**
	 * RuneCore
	 * Oct 16, 2011
	 * @author Harry Andreas<Harry@RuneCore.org>
	 */
	public enum ReaderType {
		NORMAL,
		XML;
	}
	
	/**
	 * Properties of the connection
	 */
	private final Properties cP = new Properties();
	
	/**
	 * Instance of the connection
	 */
	private Connection connection;
	
	/**
	 * Constructor
	 * @throws Exception
	 */
	public SQLConnection(String name, ReaderType t) throws Exception {
		if(t == ReaderType.NORMAL) {
			cP.load(new FileReader("./data/sql/"+name));
		} else if(t == ReaderType.XML) {
			cP.loadFromXML(new FileInputStream("./data/sql/"+name));
		} else {
			throw new Exception("unsupported reading type");
		}
		createConnection();
		Launch.getEnv().getLogger().info("Connected to "+cP.getProperty("dbName")+"@"+cP.getProperty("address"));
	}
	
	/**
	 * 
	 * @throws Exception 
	 */
	private void createConnection() throws Exception {
		setConnection(DriverManager.getConnection("jdbc:mysql://"+cP.getProperty("address")+"/"+cP.getProperty("dbName"), cP.getProperty("user"), cP.getProperty("password")));
	}

	/**
	 * @param connection the connection to set
	 */
	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	/**
	 * @return the connection
	 */
	public Connection getConnection() {
		return connection;
	}
}